import JSZip from "jszip";
import FileSaver from "file-saver";
import dayjs from "dayjs";

interface ImageData {
  name: string;
  imgData: string;
}

// 提取图片名称
const extractFileName = (url: string): string => {
  const match = url.match(/\/([^/]+)$/); // 匹配 URL 中最后一个斜杠后的部分
  return match ? match[1] : ""; // 返回匹配到的文件名
};

/**
 * 批量下载图片并生成zip包
 * @param sourceList 图片列表数组
 * @param zipName 文件夹名称，如果不传就取当前时间戳
 */
export async function downloadZip(sourceList: string[], zipName = "") {
  zipName = zipName ? zipName : dayjs(new Date()).format("YYYYMMDDHHmmss");
  const zip = new JSZip();
  const fileFolder = zip.folder(zipName); // 创建 zipName 文件夹
  const fileList: ImageData[] = [];

  // 执行图片下载和添加到ZIP的操作
  const loadImage = (src: string, name: string): Promise<ImageData> => {
    return new Promise((resolve, reject) => {
      const fileSrc = src + "?s=" + Math.random().toString();
      fetch(fileSrc)
        .then(response => response.blob())
        .then(blob => {
          const reader = new FileReader();
          reader.onloadend = () => {
            const base64data = reader.result as string;
            resolve({
              name,
              imgData: base64data.split(",")[1] // 移除 "data:image/xxx;base64," 部分
            });
          };
          reader.onerror = () => {
            reject(new Error("Failed to read image data"));
          };
          reader.readAsDataURL(blob);
        })
        .catch(() => {
          reject(new Error("Failed to fetch image"));
        });
    });
  };

  // 遍历所有图片并处理
  for (let i = 0; i < sourceList.length; i++) {
    const qrCode = sourceList[i];
    const picName = extractFileName(qrCode); // 提取图片名称
    try {
      const { name, imgData } = await loadImage(qrCode, picName);
      fileList.push({ name, imgData });
    } catch (error) {
      console.error(`Error loading image ${qrCode}: ${error.message}`);
    }
  }

  // 所有图片加载完成后，打包并下载ZIP文件
  if (fileList.length > 0) {
    fileList.forEach(({ name, imgData }) => {
      fileFolder?.file(name, imgData, { base64: true });
    });

    zip.generateAsync({ type: "blob" }).then(content => {
      FileSaver.saveAs(content, zipName + ".zip");
    });
  }
}
